package net.openl10n.packaging.document;

import net.openl10n.api.document.Document;
import net.openl10n.opc4j.PackagePart;
import net.openl10n.opc4j.exceptions.InvalidFormatException;
import net.openl10n.packaging.AbstractJaxbContentPart;
import net.openl10n.packaging.OpenLocPartContainer;
import net.openl10n.packaging.OpenLocPartFactory;
import net.openl10n.packaging.OpenLocPartFactoryManager;

import com.google.common.collect.ImmutableList;

public class DocumentPart extends AbstractJaxbContentPart{
	public static final String CONTENT_TYPE = "application/openl10n.document.main+xml";
	public static final String TARGET_NAME = "/#/document.xml";
	public static final String RELATIONSHIP_TYPE = "http://schemas.openl10n.net/document/main";

	private Document document;
	
	public static final OpenLocPartFactory<DocumentPart> FACTORY = 
		new OpenLocPartFactory<DocumentPart>() {
			@Override
			public DocumentPart create(OpenLocPartContainer container, PackagePart part, OpenLocPartFactoryManager partFactoryManager) {
				return new DocumentPart(container, part, partFactoryManager);
			}

			@Override
			public String getContentType() {
				return CONTENT_TYPE;
			}

			@Override
			public String getRelationshipType() {
				return RELATIONSHIP_TYPE;
			}

			@Override
			public Class<DocumentPart> getTargetClass(){
				return DocumentPart.class;
			}
			
			@Override
			protected String getPartNamePattern() {
				return TARGET_NAME;
			};
		};
	
	protected DocumentPart(OpenLocPartContainer container, PackagePart part, OpenLocPartFactoryManager partFactoryManager){
		super(container, part, partFactoryManager); 
	}

	public ImmutableList<DocumentPart> getDocumentParts(){
		return getPartsOfType(DocumentPart.class);
	}

	public DocumentPart addDocumentPart(){
		try{
			DocumentPart documentPart = addNewPart(DocumentPart.class);
			return documentPart;
		}
		catch(InvalidFormatException e){
			throw new RuntimeException(e);
		}
	}
	
	public ContentPart addContentPart(){
		try{
			ContentPart contentPart = addNewPart(ContentPart.class);
			return contentPart;
		}
		catch(InvalidFormatException e){
			throw new RuntimeException(e);
		}
	}
	
	public ContentPart getContentPart(){
		return getPartOfType(ContentPart.class);
	}

	public Document getDocument(){
		if(document == null){
			document = loadOrCreateJaxbObject(Document.class);
		}
		return document;
	}

	public void setDocument(Document document) {
		this.document = document;
	}
	
	@Override
	protected void onClose() {
		if(document != null)
			saveJaxbObject(document);
		super.onClose();
	}
	
}
